<template>
  <!-- :showUploadList="false" -->
  <a-upload
    v-model:file-list="fileList"
    :action="action"
    :data="dataCallback"
    :headers="headers"
    @change="onChange"
    :beforeUpload="onBeforeUpload"
    ref="uploadLocalRef"
  >
    <a-button @click="onClick" :loading="loading" :disabled="loading">
      <upload-outlined></upload-outlined>
      本地上传
    </a-button>
  </a-upload>
  <a-alert
    v-if="warning"
    show-icon
    message="所在路径存在同名同后缀冲突,点击确认后将在本文件命名后加'_1'"
    type="warning"
    closable
    style="margin-top: 5px"
  />
</template>
<script setup>
import { ref } from 'vue'
import { useDataSourceManager, useUploadLocalRef } from './provide-context.js'
import { message as Message } from 'ant-design-vue'
import { useAccountStore } from '@/stores/account'
import { storeToRefs } from 'pinia'
import { UploadOutlined } from '@ant-design/icons-vue'
import { useVModel } from '@vueuse/core'
import mockAPI from '@/api/simple-mock.js'
import { checkFileNameExist, relationUpload } from '@/api/db.js'
import { useDbType } from './provide-context.js'
import { rewriteURL } from '@/api/db.js'
/**
 * 入参
 */
let props = defineProps({
  params: { type: Object, default: () => ({}) },
  files: { tyep: Array, default: () => [] },
  file: {},
  loading: { type: Boolean, default: () => false },
  data: { required: true },
})
/**
 * 事件定义
 */
let emit = defineEmits(['end', 'start', 'update:loading'])
/**
 * 全局
 */
//调整成parentid
let { update } = useDataSourceManager()
let uploadLocalRef = useUploadLocalRef()
/**
 * 双向绑定
 */
let loading = useVModel(props, 'loading', emit)
/**
 * 用户信息
 */
let accountStore = useAccountStore()
let account = storeToRefs(accountStore)
/**
 * 交互
 */
let fileList = ref([])
let warning = ref(false)
function onBeforeUpload(file) {
  fileList.value = []
  let filename = file.name || ''
  let filetype = filename.split('.').pop()
  if (filename.includes('.')) {
    filename = filename.split('.').slice(0, -1).join('.')
  }
  if (!/^[\u4e00-\u9fa5_a-zA-Z0-9+-]+$/.test(filename)) {
    Message.error(
      `上传失败<文件名只能是中文、下划线、连字符、加号、数字、英文!>`,
    )
    setTimeout(() => {
      fileList.value = fileList.value.filter(f => {
        return !(
          file.lastModified === f.lastModified &&
          file.size === f.size &&
          file.name === f.name
        )
      })
    })
    return false
  }

  //检测是否存在文件
  loading.value = true
  checkFileNameExist(
    {
      fileName: filename,
      fileType: filetype,
      parentId: props.data.parentId,
    },
    dbType,
  )
    .then(result => {
      warning.value = result?.data
      loading.value = false
    })
    .catch(e => {
      loading.value = false
    })

  return false
}
let dbType = useDbType()
/**
 * submit
 */
async function submit({ description }) {
  if (fileList.value.length === 0) {
    Message.warn('请上传关系文件')
    throw '请上传关系文件'
  }
  let formData = new FormData()
  formData.append('file', fileList.value?.[0]?.originFileObj)
  formData.append('id', props.data.dataId)
  formData.append('description', description)
  formData.append('parentId', props.data.parentId)
  await relationUpload(formData, dbType)
  console.log('update建立关系成功!')
  Message.success('建立关系成功!')
}

defineExpose({
  submit,
})
let onChange = info => {
  if (info.file.status === 'done') {
    loading.value = false
    if (!info?.file?.response?.success) {
      fileList.value = []
      Message.error(
        `上传失败<${info?.file?.response?.errorMessage || 'error'}>`,
      )
      return
    }
    emit('end')
    files.value = [{ fileName: info.file.name, dataId: 123 }]
    try {
      //刷新列表
      update()
    } catch (e) {}
  } else if (info.file.status === 'error') {
    emit('end')
    loading.value = false
    Message.error(`上传失败<${info?.file?.error?.message || 'error'}>`)
  }
}
let headers = {
  Authorization: 'Bearer ' + account.token.value,
}
function dataCallback() {
  return {
    parentId: props.data.parentId,
    gmtBatchUpload: batchTime.value,
    ...props.params,
  }
}
/**
 * 设置上传批次时间
 */
let batchTime = ref()
function onClick() {
  batchTime.value = Date.now()
}
/**
 * 地址
 */
let action =
  (!APP_MOCK_ENABLE ? import.meta.env.VITE_APP_API_BASE || '' : '') +
  rewriteURL('/data/ed/file/upload', dbType)
</script>
